package jmotioncapture.testing.framework.util;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableRowSorter;


/**
 * @version 1.0.0
 * @author  Kenneth
 */
public class TwoFilterTable extends JPanel 
{
    private static final long serialVersionUID = 1;
	private JPanel createdTable = new JPanel();
    private JTextField filterText1, filterText2;
    
	//private JTable table;
    private TableRowSorter<MyTableModel> sorter;
    private JLabel lbNumber = new JLabel();
    
    private String[] columnNames;
    private JTable table; 
    private int[] columnWidth;
    private int[] columnAlignment;
    private int filterColmun1;
    private int filterColmun2;
    private MyTableModel model;
    
    private Object[][] data;

    public TwoFilterTable(String[] columnNames, Object[][] data, int[] columnWidth, int[] columnAlignment, int filterColmun1, int filterColmun2)
    {
        super();
        setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
        
        //Init all the table data
        this.columnNames = columnNames;
        this.data = data;
        this.columnWidth = columnWidth;
        this.columnAlignment = columnAlignment;
        this.filterColmun1 = filterColmun1;
        this.filterColmun2 = filterColmun2;

        //Create a table with a sorter.
        model = new MyTableModel();
        sorter = new TableRowSorter<MyTableModel>(model);
        table = new JTable(model);
        table.setRowSorter(sorter);
        table.setPreferredScrollableViewportSize(new Dimension(500, 300));
        table.setFillsViewportHeight(true);
        

        //For the purposes of this example, better to have a single
        //selection.
        table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

        filterText1 = new JTextField();
        filterText1.setColumns(20);
        
        
        //Whenever filterText changes, invoke newFilter.
        filterText1.getDocument().addDocumentListener(
                new DocumentListener() {
                    public void changedUpdate(DocumentEvent e) {
                        newFilter();
                        lbNumber.setText("Found: " + Integer.toString(table.getRowCount()));
                    }
                    public void insertUpdate(DocumentEvent e) {
                        newFilter();
                        lbNumber.setText("Found: " + Integer.toString(table.getRowCount()));
                    }
                    public void removeUpdate(DocumentEvent e) {
                        newFilter();
                        lbNumber.setText("Found: " + Integer.toString(table.getRowCount()));
                    }
                });
        
        //Filter2
        filterText2 = new JTextField();
        filterText2.setColumns(20);
        
        
        //Whenever filterText changes, invoke newFilter.
        filterText2.getDocument().addDocumentListener(
                new DocumentListener() {
                    public void changedUpdate(DocumentEvent e) {
                        newFilter2();
                        lbNumber.setText("Found: " + Integer.toString(table.getRowCount()));
                    }
                    public void insertUpdate(DocumentEvent e) {
                        newFilter2();
                        lbNumber.setText("Found: " + Integer.toString(table.getRowCount()));
                    }
                    public void removeUpdate(DocumentEvent e) {
                        newFilter2();
                        lbNumber.setText("Found: " + Integer.toString(table.getRowCount()));
                    }
                });
        
        
        
        for (int i = 0; i < columnNames.length; i++) 
        {
        	DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
        	renderer.setHorizontalAlignment(this.columnAlignment[i]);
        	TableColumn column = table.getColumnModel().getColumn(i);
        	
            column.setPreferredWidth(this.columnWidth[i]); //third column is bigger
            column.setCellRenderer(renderer);
            
        }


        //Create the scroll pane and add the table to it.
        JScrollPane scrollPane = new JScrollPane(table);

        //Add the scroll pane to this panel.
        add(scrollPane);

       
        
        //Panel GUI setting
        GridBagLayout gridbag = new GridBagLayout();
        //GridBagConstraints c = new GridBagConstraints();
        
        JPanel panel = new JPanel();
        panel.setLayout(gridbag);
        
        final GridBagConstraints gridBagConstraints = new GridBagConstraints();
        gridBagConstraints.fill = GridBagConstraints.HORIZONTAL;
        panel.add(filterText1, gridBagConstraints);
        panel.add(filterText2, gridBagConstraints);
        
        createdTable.add(panel);
    }
    
    /**
     * Set the cell to edit or not
     * @param editCell Set to true if the cells is editable, otherwise set to false
     */
    public void setCellEditable(boolean editCell)
    {
    	model.setCellEditable(editCell);
    }
    
    /**
     * Get the filter one text
     * @return Filter one text
     */
    public JTextField getFilterText1()
    {
    	return filterText1;
    }
    
    /**
     * Get the filter two text
     * @return Filter two text
     */
    public JTextField getFilterText2()
    {
    	return filterText2;
    }
    
    /**
     * Set the filter one text
     * @param str
     */
    public void setFilterTwoText(String str)
    {
    	filterText2.setText(str);
    }
    
    /**
     * Set the filter two text
     * @param str
     */
    public void setFilterOneText(String str)
    {
    	filterText1.setText(str);
    }

    /**
     * Get the JTable panel
     * @return JPanel of the created table
     */
    public JPanel getPanel()
    {
    	return createdTable;
    }
    
    /**
     * Return the JTable 
	 * @return  the table
	 * @uml.property  name="table"
	 */
    public JTable getTable()
    {
    	return table;
    }
    
    
    public JLabel getFoundLabel()
    {
    	return lbNumber;
    }
    
    
    public String[] getTableData()
    {
    	String[] result = new String [data.length];
    	
    	for(int i=0; i<data.length; i++)
    	{
    		String temp = Integer.toString((Integer)data[i][0]) + ",";
    		temp = temp + (String)data[i][1] + ",";
    		temp = temp + (String)data[i][2];
    		
    		System.out.println("SummaryReportTable:  " + temp);
    		
    		result[i] = temp;
    	}
    	return result;
    }
    
    /**
     * Get all the column name
     * @return Column names
     */
    private String[] getColumn()
    {
    	return columnNames;
    }
    
    /**
	 * @return  the data
	 * @uml.property  name="data"
	 */
    private Object[][] getData()
    {
    	return data;
    }
    

    class MyTableModel extends AbstractTableModel {
    	
    	private static final long serialVersionUID = 1;
        private String[] columnNames = getColumn();
        private Object[][] data = getData();
        private boolean isCellEditableBoolean = false;
        
        public int getColumnCount() {
            return columnNames.length;
        }

        public int getRowCount() {
            return data.length;
        }

        public String getColumnName(int col) {
            return columnNames[col];
        }

        public Object getValueAt(int row, int col) {
            return data[row][col];
        }

        /*
         * JTable uses this method to determine the default renderer/
         * editor for each cell.  If we didn't implement this method,
         * then the last column would contain text ("true"/"false"),
         * rather than a check box.
         */
        public Class<?> getColumnClass(int c) {
            try {
				return getValueAt(0, c).getClass();
			} catch (RuntimeException e) {
				return null;
			}
        }
        
        public boolean isCellEditable(int row, int column) {
            return isCellEditableBoolean;
        }
        
        public void setCellEditable(boolean isEditable)
        {
        	isCellEditableBoolean = isEditable;
        }

        public void setValueAt(Object value, int row, int column) {
        	data[row][column] = value;
        }

    }
    
    /** 
     * Update the row filter regular expression from the expression in
     * the text box.
     */
    private void newFilter() {
        RowFilter<MyTableModel, Object> rf = null;
        //If current expression doesn't parse, don't update.
        try {
            rf = RowFilter.regexFilter(filterText1.getText(), filterColmun1);
        } catch (java.util.regex.PatternSyntaxException e) {
            return;
        }
        sorter.setRowFilter(rf);
    }
        
    /** 
     * Update the row filter regular expression from the expression in
     * the text box.
     */
    private void newFilter2() {
        RowFilter<MyTableModel, Object> rf = null;
        //If current expression doesn't parse, don't update.
        try {
            rf = RowFilter.regexFilter(filterText2.getText(), filterColmun2);
        } catch (java.util.regex.PatternSyntaxException e) {
            return;
        }
        sorter.setRowFilter(rf);
    }
    
    public static void main(String[] args) 
    {
    	String[] columnNames = {"First Name","Last Name","Sport","# of Years","Vegetarian"};
        int[] columnWidth = {50,100,150,200,50};
        int[] columnAlignment = {JLabel.LEFT, JLabel.CENTER, JLabel.RIGHT, JLabel.LEFT, JLabel.CENTER};
        Object[][] data = {
                {"Mary", "Campione",
                    "Snowboarding", new Integer(5), new Boolean(false)},
                   {"Alison", "Huml",
                    "Rowing", new Integer(3), new Boolean(true)},
                   {"Kathy", "Walrath",
                    "Knitting", new Integer(2), new Boolean(false)},
                   {"Sharon", "Zakhour",
                    "Speed reading", new Integer(20), new Boolean(true)},
                   {"Philip", "Milne",
                    "Pool", new Integer(10), new Boolean(false)},
               };
        
        
        JFrame frame = new JFrame("Testing Data");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        
        TwoFilterTable crt = new TwoFilterTable(columnNames, data, columnWidth, columnAlignment, 0, 1);
        crt.setOpaque(true); //content panes must be opaque
        
        JPanel form = crt.getPanel();
        
        frame.add(crt, BorderLayout.CENTER);
        frame.add(form, BorderLayout.SOUTH);
        
        frame.setSize(500, 400);
        frame.setVisible(true);
    }
}
